package com.opdar.platform.gateway.namespace;

import com.opdar.platform.gateway.point.PointManager;
import com.opdar.platform.gateway.point.PointProxy;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.BeanDefinitionDecorator;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.cglib.proxy.Callback;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

/**
 * Created by shiju on 2017/12/14.
 */
public class PointManagerNamespaceHandler extends NamespaceHandlerSupport {
    @Override
    public void init() {
        registerBeanDefinitionParser("context", new BeanDefinitionParser() {
            @Override
            public BeanDefinition parse(Element element, ParserContext parserContext) {
                if(element.hasAttribute("apiClz")){
                    String apiClzStr = element.getAttribute("apiClz");
                    try {
                        Class<?> apiClz = Class.forName(apiClzStr);
                        BeanDefinitionBuilder pointManagerDefintionBuilder = BeanDefinitionBuilder.genericBeanDefinition(PointManager.class);
                        pointManagerDefintionBuilder.addConstructorArgValue(apiClz);
                        pointManagerDefintionBuilder.addConstructorArgValue(true);
                        parserContext.getRegistry().registerBeanDefinition(PointManager.class.getName(),pointManagerDefintionBuilder.getRawBeanDefinition());

                        Class<?> apiProxyClz = PointProxy.getProxyClass(apiClz);
                        BeanDefinitionBuilder apiBeanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(apiProxyClz);
                        apiBeanDefinitionBuilder.addPropertyValue("callbacks",new Callback[]{new PointProxy()});
                        AbstractBeanDefinition apiBeanDefinition = apiBeanDefinitionBuilder.getRawBeanDefinition();
                        parserContext.getRegistry().registerBeanDefinition(apiClz.getName(),apiBeanDefinition);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                //生成获取配置和设置配置的

                return null;
            }
        });
    }
}
